package com.lm.forkjoin.listener;

import com.lm.forkjoin.entry.UserData;
import org.apache.catalina.User;

import java.util.List;
import java.util.concurrent.RecursiveTask;

public class FileImportTask extends RecursiveTask<Integer> {

    private static final int THRESHOLD = 1000; // 每次处理1000条
    private final List<UserData> data;

    public FileImportTask(List<UserData> data) {
        this.data = data;
    }

    @Override
    protected Integer compute() {
        if (data.size() <= THRESHOLD) {
            // 处理小批量任务（入库操作）
            saveData(data);
            return data.size();
        } else {
            int mid = data.size() / 2;
            FileImportTask left = new FileImportTask(data.subList(0, mid));
            FileImportTask right = new FileImportTask(data.subList(mid, data.size()));

            // 异步执行子任务
            left.fork();
            int rightResult = right.compute();
            int leftResult = left.join();

            return leftResult + rightResult;
        }
    }

    private void saveData(List<UserData> users) {
        // TODO: 替换为真正的批量入库逻辑
        System.out.println("批量插入数据：" + users.size() + " 条, 当前线程: " + Thread.currentThread().getName());
    }
}
